<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <uni-search-bar 
        v-model="searchKeyword" 
        placeholder="搜索商品名称"
        @confirm="handleSearch"
        @clear="handleClearSearch"
        :focus="false"
        :show-action="false"
        bg-color="#f5f5f5"
      />
    </view>

    <!-- 分类筛选 -->
    <view class="filter-bar">
      <view class="category-list">
        <view 
          class="category-item" 
          :class="{ active: selectedCategory === '' }"
          @click="selectCategory('')"
        >
          全部
        </view>
        <view 
          v-for="category in categories" 
          :key="category"
          class="category-item" 
          :class="{ active: selectedCategory === category }"
          @click="selectCategory(category)"
        >
          {{ getCategoryName(category) }}
        </view>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="product-list">
      <view 
        v-for="product in products" 
        :key="product.id"
        class="product-item"
        @click="goToDetail(product.id)"
      >
        <view class="product-image">
          <image 
            :src="product.image_url || '/static/icons/default-product.png'" 
            mode="aspectFill"
            class="image"
            @error="handleImageError($event, product)"
          />
          <view v-if="product.is_hot" class="hot-tag">热门</view>
          <view v-if="product.is_new" class="new-tag">新品</view>
        </view>
        
        <view class="product-info">
          <view class="product-name">{{ product.name || '未知商品' }}</view>
          <view class="product-desc">{{ product.description || '暂无描述' }}</view>
          
          <view class="product-price">
            <view class="points-price">
              <text class="price-number">{{ product.points_price || 0 }}</text>
              <text class="price-unit">积分</text>
            </view>
            <view v-if="product.original_price && product.original_price > 0" class="original-price">
              原价: ¥{{ product.original_price.toFixed(2) }}
            </view>
          </view>
          
          <view class="product-stock">
            <text v-if="product.stock > 0" class="in-stock">
              库存: {{ product.stock }}
            </text>
            <text v-else class="out-of-stock">缺货</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore" class="load-more" @click="loadMore">
      <text v-if="!loading">加载更多</text>
      <text v-else>加载中...</text>
    </view>

    <!-- 空状态 -->
    <view v-if="!loading && products.length === 0" class="empty-state">
      <image src="/static/icons/empty.png" class="empty-icon" />
      <text class="empty-text">暂无商品</text>
    </view>

    <!-- 加载中 -->
    <view v-if="loading && products.length === 0" class="loading-state">
      <uni-load-more status="loading" />
    </view>
  </view>
</template>

<script>
import productsApi from '@/api/products'
import productValidator, { processApiResponse, formatListForDisplay } from '@/utils/productDataValidator'
import { handleError } from '@/utils/errorHandler'
import { showLoading, hideLoading, isLoading } from '@/utils/loadingManager'

export default {
  name: 'ProductsListPage',
  data() {
    return {
      products: [],
      categories: ['print', 'copy', 'binding', 'other'],
      searchKeyword: '',
      selectedCategory: '',
      loading: false,
      hasMore: true,
      page: 1,
      limit: 20,

      retryCount: 0,
      maxRetries: 3,
      categoryNames: {
        'print': '打印',
        'copy': '复印',
        'binding': '装订',
        'other': '其他'
      }
    }
  },
  
  onLoad() {
    this.initPageData()
  },
  
  onShow() {
    // 页面显示时刷新数据，确保数据是最新的
    if (this.products.length > 0) {
      // 如果已有数据，静默刷新
      this.refreshData(false)
    }
  },
  
  onPullDownRefresh() {
    this.refreshData()
  },
  
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore()
    }
  },
  
  methods: {
    // 初始化页面数据
    async initPageData() {
      const loadingKey = 'init_products'
      
      try {
        showLoading(loadingKey, { title: '加载商品列表...' })
        await this.loadProducts(true)
      } catch (error) {
        console.error('初始化页面数据失败:', error)
        handleError(error, { action: 'init_products' }, {
          showToast: false,
          showModal: true,
          title: '加载失败',
          onRetry: () => this.initPageData()
        })
        this.handleApiFailure()
      } finally {
        hideLoading(loadingKey)
      }
    },
    
    // 处理API失败情况
    handleApiFailure() {
      this.products = []
      this.hasMore = false
      
      uni.showToast({
        title: '暂无商品数据',
        icon: 'none',
        duration: 2000
      })
    },
    
    // 加载商品列表
    async loadProducts(reset = false, showLoadingIndicator = true) {
      if (this.loading || isLoading('load_products')) return
      
      this.loading = true
      const loadingKey = reset ? 'refresh_products' : 'load_more_products'
      
      try {
        const params = {
          page: reset ? 1 : this.page,
          limit: this.limit,
          category: this.selectedCategory || undefined,
          search: this.searchKeyword || undefined
        }
        
        console.log('正在加载商品列表，参数:', params)
        
        if (showLoadingIndicator && !reset) {
          showLoading(loadingKey, { title: '加载更多商品...' })
        }
        
        const response = await productsApi.getProductList(params)
        
        // 使用数据验证器处理API响应
        const processedResponse = processApiResponse(response)
        
        if (processedResponse.success) {
          let newProducts = []
          
          // 处理不同的响应数据结构
          if (Array.isArray(processedResponse.data)) {
            newProducts = processedResponse.data
          } else if (processedResponse.data && processedResponse.data.products) {
            newProducts = processedResponse.data.products
          } else if (processedResponse.data) {
            newProducts = [processedResponse.data]
          }
          
          // 格式化商品数据用于显示
          const formattedProducts = formatListForDisplay(newProducts)
          
          if (reset) {
            this.products = formattedProducts
            this.page = 1
            this.retryCount = 0 // 重置重试计数
          } else {
            this.products = [...this.products, ...formattedProducts]
          }
          
          // 处理分页信息
          if (response && response.data && response.data.pagination) {
            this.hasMore = response.data.pagination.page < response.data.pagination.pages
            this.page = response.data.pagination.page + 1
          } else {
            // 如果没有分页信息，根据返回数据量判断
            this.hasMore = formattedProducts.length >= this.limit
            this.page += 1
          }
          
          console.log(`成功加载 ${formattedProducts.length} 个商品`)
          
        } else {
          throw new Error(processedResponse.message || 'API返回错误')
        }
      } catch (error) {
        console.error('加载商品列表失败:', error)
        this.retryCount++
        
        // 使用统一错误处理
        const errorInfo = handleError(error, { 
          action: 'load_products',
          reset,
          retryCount: this.retryCount 
        }, {
          showToast: false
        })
        
        // 显示错误提示，提供重试选项
        if (this.retryCount <= this.maxRetries) {
          uni.showModal({
            title: '加载失败',
            content: errorInfo.message || '商品列表加载失败，请检查网络后重试',
            confirmText: '重试',
            cancelText: '取消',
            success: (res) => {
              if (res.confirm) {
                this.retryCount = 0
                setTimeout(() => {
                  this.loadProducts(reset)
                }, 1000)
              } else {
                this.handleApiFailure()
              }
            }
          })
        } else {
          this.handleApiFailure()
        }
      } finally {
        this.loading = false
        hideLoading(loadingKey)
        if (reset) {
          uni.stopPullDownRefresh()
        }
      }
    },
    
    // 刷新数据
    refreshData(showLoading = true) {
      this.loadProducts(true, showLoading)
    },
    
    // 加载更多
    loadMore() {
      this.loadProducts()
    },
    
    // 搜索商品
    handleSearch() {
      this.loadProducts(true)
    },
    
    // 清除搜索
    handleClearSearch() {
      this.searchKeyword = ''
      this.loadProducts(true)
    },
    
    // 选择分类
    selectCategory(category) {
      this.selectedCategory = category
      this.loadProducts(true)
    },
    
    // 获取分类名称
    getCategoryName(category) {
      return this.categoryNames[category] || category
    },
    
    // 跳转到商品详情
    goToDetail(productId) {
      if (!productId) {
        uni.showToast({
          title: '商品信息错误',
          icon: 'none'
        })
        return
      }
      
      console.log('跳转到商品详情，ID:', productId)
      uni.navigateTo({
        url: `/pages/products/detail?id=${productId}`
      })
    },
    
    // 获取友好的错误信息
    getErrorMessage(error) {
      if (!error) return '未知错误'
      
      const message = error.message || error.toString()
      
      if (message.includes('timeout')) {
        return '请求超时，请检查网络连接'
      } else if (message.includes('network') || message.includes('fail')) {
        return '网络连接失败，请检查网络设置'
      } else if (message.includes('404')) {
        return '服务暂时不可用'
      } else if (message.includes('500')) {
        return '服务器内部错误'
      } else {
        return '加载失败，请稍后重试'
      }
    },
    
    // 处理图片加载错误
    handleImageError(event, product) {
      console.warn('商品图片加载失败:', product.id, event)
      // 设置默认图片
      this.$set(product, 'image_url', '/static/icons/default-product.png')
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-bar {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.filter-bar {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.category-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.category-item {
  padding: 12rpx 24rpx;
  background-color: #f0f0f0;
  border-radius: 20rpx;
  font-size: 28rpx;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &.active {
    background-color: #007aff;
    color: #fff;
  }
  
  &:active {
    transform: scale(0.95);
  }
}

.product-list {
  padding: 0 20rpx;
}

.product-item {
  display: flex;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  }
}

.product-image {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.hot-tag, .new-tag {
  position: absolute;
  top: 0;
  right: 0;
  padding: 4rpx 8rpx;
  font-size: 20rpx;
  color: #fff;
  border-radius: 0 8rpx 0 8rpx;
}

.hot-tag {
  background-color: #ff4757;
}

.new-tag {
  background-color: #2ed573;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.product-desc {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 12rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
  max-height: 2.8em; /* 2行的高度 */
  word-break: break-all;
}

.product-price {
  margin-bottom: 8rpx;
}

.points-price {
  display: flex;
  align-items: baseline;
}

.price-number {
  font-size: 36rpx;
  font-weight: bold;
  color: #ff4757;
}

.price-unit {
  font-size: 24rpx;
  color: #ff4757;
  margin-left: 4rpx;
}

.original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
  margin-top: 4rpx;
}

.product-stock {
  font-size: 24rpx;
}

.in-stock {
  color: #2ed573;
}

.out-of-stock {
  color: #ff4757;
}

.load-more {
  text-align: center;
  padding: 40rpx;
  font-size: 28rpx;
  color: #666;
  cursor: pointer;
  
  &:active {
    opacity: 0.7;
  }
}

.empty-state {
  text-align: center;
  padding: 100rpx 40rpx;
}

.empty-icon {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.loading-state {
  padding: 100rpx 40rpx;
}
</style>